import { useRequest } from 'ahooks';
import {
  Space, message, Select
} from 'antd';
import {
  Key,
  useCallback,
  useEffect,
  useState
} from 'react';

import * as APIS from '../../../../constants/api-constants';

const { Option, OptGroup } = Select;

interface SearchProps {
  currentTemplateUuid: string | undefined,
  currentQuestionnaireUuid: string | undefined,
  setCurrentQuestionnaireUuid: (currentQuestionnaireUuid?: string) => void,
  setTQUuid: (templateUuid: string, questionnaireUuid: string) => void,
  requestTableDataByTQUuid: (
    currentPage: number,
    templateUuid?: string,
    questionnaireUuid?: string
  ) => void,
  clearTable: () => void
}

export default ({
  currentTemplateUuid,
  currentQuestionnaireUuid,
  setTQUuid,
  setCurrentQuestionnaireUuid,
  clearTable,
  requestTableDataByTQUuid
}: SearchProps) => {
  const [questionnaireDisable, setQuestionnaireDisable] = useState(true);
  const [
    currentQuestionnaireValue,
    setCurrentQuestionnaireValue
  ] = useState('');
  const [templateValue, setTemplateValue] = useState('');
  const [templateOptionList, setTemplateOptionList] = useState<
    Answer.TemplateItemOption[] | undefined
  >();
  const [questionnaireOptionList, setQuestionnaireOptionList] = useState<
    Answer.QuestionnaireItemOption[] | undefined
  >();

  /**
   * get questionnaireList
   */
  const {
    run: requestQuestionnaireOptionList,
    loading: questionnaireLoading
  } = useRequest((
    questionnaireName: string,
    templateUuid: string
  ) => ({
    url: APIS.QUESTIONNAIRE_OPTION_LIST,
    method: 'GET',
    params: {
      name: questionnaireName,
      templateUuid,
      isAttachAll: true
    }
  }), {
    debounceInterval: 600,
    manual: true,
    onSuccess: (result) => {
      const currentQuestionnaireOptionList = result.data;
      setQuestionnaireDisable(false);
      setQuestionnaireOptionList(currentQuestionnaireOptionList);

      const foundQuestionOption = currentQuestionnaireOptionList.find(
        (questionnaireOption: Answer.QuestionnaireItemOption) => (
          questionnaireOption.uuid === currentQuestionnaireUuid
        )
      );

      if (foundQuestionOption?.name && currentQuestionnaireUuid) {
        setCurrentQuestionnaireValue(foundQuestionOption?.name);
        requestTableDataByTQUuid(
          1,
          currentTemplateUuid,
          currentQuestionnaireUuid
        );
      }
    },
    onError: () => {
      message.error('二级选项列表生成错误');
    },
  });

  /**
   * get templateList
   */
  const {
    run: requestTemplateOptionList,
    loading: templateLoading
  } = useRequest((templateName: string) => ({
    url: APIS.TEMPLATE_OPTION_LIST,
    method: 'GET',
    params: {
      title: templateName,
      isAttachAll: true
    }
  }), {
    debounceInterval: 600,
    manual: true,
    onSuccess: (result) => {
      const currentTemplateOptionList = result.data;
      setTemplateOptionList(currentTemplateOptionList);

      if (currentTemplateUuid) {
        // 需要请求
        requestQuestionnaireOptionList('', currentTemplateUuid);
      }
    },
    onError: () => {
      message.error('template列表生成错误');
    },
  });

  useEffect(() => {
    requestTemplateOptionList('');
  }, []);

  // 根据 templateUuid 改变 templateTitle
  useEffect(() => {
    let templateOptionValue = '';
    templateOptionList?.forEach((
      templateGroupOption: Answer.TemplateItemOption
    ) => {
      const foundTemplateOption = templateGroupOption
        .templateOption
        .find((templateOptionItem) => (
          templateOptionItem.uuid === currentTemplateUuid
        ));

      if (foundTemplateOption?.title) {
        templateOptionValue = foundTemplateOption?.title;
      }
    });

    if (templateOptionValue && currentTemplateUuid) {
      setTemplateValue(templateOptionValue);
    }
  }, [currentTemplateUuid, templateOptionList]);

  const handleTemplateSelected = useCallback((key: string) => {
    clearTable();
    setTQUuid(key, '');
    setCurrentQuestionnaireValue('');
    requestQuestionnaireOptionList('', key);
  }, []);

  const handleQuestionnaireSelected = useCallback(
    (
      value: string, key: Key | undefined
    ) => {
      const uuid = key ? `${key}` : '';
      setCurrentQuestionnaireValue(value);
      setCurrentQuestionnaireUuid(uuid);
      requestTableDataByTQUuid(1, currentTemplateUuid, uuid);
    }, [currentTemplateUuid]
  );

  return (
    <>
      <Space
        direction="vertical"
        style={{ width: '100%', justifyContent: 'space-between' }}
      >
        <span>
          问卷选择：
          <Select
            showSearch
            placeholder="请选择"
            value={templateValue}
            disabled={templateLoading}
            loading={templateLoading}
            style={{ width: 350 }}
            onSelect={(
              _value: string,
              option: any
            ) => {
              const { key } = option;
              handleTemplateSelected(key);
            }}
            onSearch={(templateName: string) => {
              requestTemplateOptionList(templateName);
            }}
          >
            {templateOptionList?.map(({ label, templateOption }) => (
              <OptGroup label={label} key={label}>
                {
                  templateOption.map(({ title, uuid }) => (
                    <Option key={uuid} value={title}>{title}</Option>
                  ))
                }
              </OptGroup>
            ))}
          </Select>
        </span>
        <span>
          二级问卷：
          <Select
            showSearch
            value={currentQuestionnaireValue}
            disabled={questionnaireDisable || questionnaireLoading}
            placeholder="请选择"
            loading={questionnaireLoading}
            style={{ width: 350 }}
            onSelect={(
              value: string,
              option
            ) => {
              const { key } = option;
              handleQuestionnaireSelected(value, key);
            }}
            onSearch={(questionnaireName: string) => {
              if (currentTemplateUuid) {
                requestQuestionnaireOptionList(
                  questionnaireName,
                  currentTemplateUuid
                );
              }
            }}
          >
            {questionnaireOptionList?.map(({ name, uuid }) => (
              <Option key={uuid} value={name}>{name}</Option>
            ))}
          </Select>
        </span>
      </Space>
    </>
  );
};
